package com.hermit.qmst.service;

import android.app.Instrumentation;
import android.app.IntentService;
import android.content.Context;
import android.content.Intent;
import android.os.SystemClock;
import android.telephony.TelephonyManager;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.widget.Toast;

import com.hermit.qmst.aidl.ITelephony;
import com.hermit.qmst.tools.Log;

import java.lang.reflect.Method;

/**
 * Created by hermithermit on 15/2/18.
 */
public class AutoAnswerIntentService extends IntentService {


    public AutoAnswerIntentService(){
        super("AutoAnswerIntentService");
    }


    /**
     * Creates an IntentService.  Invoked by your subclass's constructor.
     *
     * @param name Used to name the worker thread, important only for debugging.
     */
    public AutoAnswerIntentService(String name) {
        super(name);
    }

    private void answer() throws Exception{

        Instrumentation instrumentation = new Instrumentation();
        instrumentation.sendPointerSync(MotionEvent.obtain(SystemClock.uptimeMillis(), SystemClock.uptimeMillis(), 0, 40.0F, 230.0F, 0));
        instrumentation.sendPointerSync(MotionEvent.obtain(SystemClock.uptimeMillis(), SystemClock.uptimeMillis(), 1, 40.0F, 230.0F, 0));
    }

    private void answerPhoneAidl(Context paramContext)throws Exception{

        TelephonyManager telephonyManager = (TelephonyManager)getSystemService(Context.TELEPHONY_SERVICE);
        Method method = Class.forName(telephonyManager.getClass().getName()).getDeclaredMethod("getITelephony",new Class[0]);
        method.setAccessible(true);
        ITelephony iTelephony = (ITelephony)method.invoke(telephonyManager,new Object[0]);
        iTelephony.silenceRinger();
        iTelephony.answerRingingCall();
    }

    private void answerRingingCall(Context pContext) throws Exception{

        Intent intent1 = new Intent("android.intent.action.HEADSET_PLUG");
        intent1.addFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);
        intent1.putExtra("state", 1);
        intent1.putExtra("microphone", 1);
        intent1.putExtra("name", "Headset");
        pContext.sendOrderedBroadcast(intent1, "android.permission.CALL_PRIVILEGED");

        Intent intent2 = new Intent(Intent.ACTION_MEDIA_BUTTON);
        KeyEvent keyEvent1 = new KeyEvent(KeyEvent.ACTION_DOWN,
                KeyEvent.KEYCODE_HEADSETHOOK);
        intent2.putExtra("android.intent.extra.KEY_EVENT",
                keyEvent1);
        pContext.sendOrderedBroadcast(intent2,
                "android.permission.CALL_PRIVILEGED");

        Intent intent3 = new Intent(Intent.ACTION_MEDIA_BUTTON);
        KeyEvent keyEvent2 = new KeyEvent(KeyEvent.ACTION_UP,
                KeyEvent.KEYCODE_HEADSETHOOK);
        intent3.putExtra("android.intent.extra.KEY_EVENT",
                keyEvent2);
        pContext.sendOrderedBroadcast(intent3,
                "android.permission.CALL_PRIVILEGED");

        Intent intent4 = new Intent(Intent.ACTION_HEADSET_PLUG);
        intent4.addFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);
        intent4.putExtra("state", 0);
        intent4.putExtra("microphone", 1);
        intent4.putExtra("name", "Headset");
        pContext.sendOrderedBroadcast(intent4,
                "android.permission.CALL_PRIVILEGED");

    }


    private void answerPhoneHeadsethook(Context paramContext) throws Exception{
        Intent intent1 = new Intent("android.intent.action.MEDIA_BUTTON");
        intent1.putExtra("android.intent.extra.KEY_EVENT", new KeyEvent(KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_HEADSETHOOK));
        paramContext.sendOrderedBroadcast(intent1, "android.permission.CALL_PRIVILEGED");
        Intent intent2 = new Intent("android.intent.action.MEDIA_BUTTON");
        intent1.putExtra("android.intent.extra.KEY_EVENT", new KeyEvent(KeyEvent.ACTION_UP, KeyEvent.KEYCODE_HEADSETHOOK));
        paramContext.sendOrderedBroadcast(intent1, "android.permission.CALL_PRIVILEGED");
    }




    /**
     * This method is invoked on the worker thread with a request to process.
     * Only one Intent is processed at a time, but the processing happens on a
     * worker thread that runs independently from other application logic.
     * So, if this code takes a long time, it will hold up other requests to
     * the same IntentService, but it will not hold up anything else.
     * When all requests have been handled, the IntentService stops itself,
     * so you should not call {@link #stopSelf}.
     *
     * @param intent The value passed to {@link
     *               Context#startService(Intent)}.
     */
    @Override
    protected void onHandleIntent(Intent intent) {

        Context context = getBaseContext();

        try {
            answerPhoneAidl(context);
            Log.i("AutoAnswerIntentService","onHandleIntent",true);
        }catch (Exception e){
            try {
                answerRingingCall(context);
                Log.i("AutoAnswerIntentService","answerRingingCall",true);
            }catch (Exception e2){
                try {
                    answerPhoneHeadsethook(context);
                    Log.i("AutoAnswerIntentService","answerPhoneHeadsethook",true);
                }catch (Exception e3){
                    try {
                        answer();
                        Log.i("AutoAnswerIntentService","answer",true);
                    }catch (Exception e4){
                        Toast.makeText(context,"您的手机不能自动接听，请手动听!",Toast.LENGTH_SHORT).show();
                    }
                }
            }

        }

    }
}
